package org.fnzn.service.Impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.fnzn.bean.LrdUser;
import org.fnzn.bean.LrdUserrole;
import org.fnzn.dao.LrdRoleMapper;
import org.fnzn.dao.LrdUserroleMapper;
import org.fnzn.wechat.bean.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.fnzn.bean.vo.User;
import org.fnzn.core.Constants;
import org.fnzn.core.Page;
import org.fnzn.core.Result;
import org.fnzn.dao.LrdOrgMapper;
import org.fnzn.dao.LrdUserMapper;
import org.fnzn.service.LrdOrgService;
import org.fnzn.service.LrdUserService;
import org.fnzn.service.base.AbstractService;
import org.fnzn.util.Base64;
import org.fnzn.util.DicReplace;
import org.fnzn.util.MD5;
import org.fnzn.util.ResultGenerator;
import org.fnzn.util.SendHttpService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class LrdUserServiceImpl extends AbstractService<LrdUser> implements LrdUserService {

    @Autowired(required = false)
	private LrdUserMapper lrdUserMapper;
	@Autowired
	private LrdOrgMapper lrdOrgMapper;
    @Autowired(required = false)
	private LrdRoleMapper lrdRoleMapper;
	@Autowired
	private LrdOrgService lrdOrgService;
    @Autowired(required = false)
	private LrdUserroleMapper lrdUserroleMapper;

	@Override
	public Result queryTree(HttpServletRequest request, Map<String, Object> map) {
		Object orgCd = map.get("orgCd");
		User user = (User) request.getSession().getAttribute("user");
		if (orgCd == null) {
			List<Map<String, Object>> userRole = user.getROLE_CD();
			String roleFw = "";
			for (Map<String, Object> map2 : userRole) {
				roleFw = map2.get("ROLE_FW") + roleFw;
			}
			if (roleFw.contains(Constants.ROLE_FW_1)) {// 所有

			} else if (roleFw.contains(Constants.ROLE_FW_2)) { // 本级及下级
				String childIds = lrdOrgService.getChilds(user.getOrgCD());
				map.put("orgCds", "(" + childIds + ")");
			} else if (roleFw.contains(Constants.ROLE_FW_0)) {// 本级
				String orgCD = user.getOrgCD();
				map.put("orgCd", orgCD);
			}
		}
		if (!Constants.SLS_CORP.equals(user.getCorpCD())) {
			map.put("corpCd", user.getCorpCD());
		}
		Page page = new Page();
		if (map.get("limit") != null && map.get("page") != null) {
			page.setLimit(Integer.parseInt(map.get("limit").toString()));
			page.setPage(Integer.parseInt(map.get("page").toString()));
		}
		PageHelper.startPage(page.getPage(), page.getLimit(), true);
		List<Map<String, Object>> resultList = lrdUserMapper.queryList(map);
		for (Map<String, Object> map2 : resultList) {
			List<Map<String, Object>> userRoles = lrdUserMapper.queryUserRole(map2);
			String name = "";
			String roleCds = "";
			for (Map<String, Object> map3 : userRoles) {
				if (map3.get("roleName") != null) {
					name = name + map3.get("roleName") + ",";
				}
				if (map3.get("roleCd") != null) {
					roleCds += map3.get("roleCd") + ",";
				}
			}
			if (StringUtils.isNotBlank(name)) {
				name = name.substring(0, name.length() - 1);
			}
			if (StringUtils.isNotBlank(roleCds)) {
				roleCds = roleCds.substring(0, roleCds.length() - 1);
			}
			map2.put("name", name);
			map2.put("roleCds", roleCds);
		}
		Map<String, String> dicMap = new HashMap<String, String>();
		dicMap.put("jlFlag", "USER_STATUS");
		DicReplace.replaceDic(resultList, dicMap);
		page.setRows(resultList);
		page.setTotal(new PageInfo<Map<String, Object>>(resultList).getTotal());
		return ResultGenerator.genSuccessResult(page);

	}

	@Override
	public Result resetPwd(LrdUser lrdUser, HttpServletRequest request) {
		// TODO Auto-generated method stub
		Map<String, Object> map2 = new HashMap<>();
		User user = (User) request.getSession().getAttribute("user");
		map2.put("userId", user.getUser_id());
		String newpwd = MD5.getMD5(Constants.PASSWORD);
		LrdUser newlrdUser = new LrdUser();
		newlrdUser.setUserId(lrdUser.getUserId());
		newlrdUser.setPassword(newpwd);
		update(newlrdUser);
		return ResultGenerator.genSuccessResult();
	}

	@Override
	public Result queryInsert(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> resultmap = new HashMap<String, Object>();
		// 查询当前登录用户的拥有机构列表
		User user = (User) request.getSession().getAttribute("user");
		List<Map<String, Object>> userRole = user.getROLE_CD();
		String roleFw = "";
		String roleCd = "";
		for (Map<String, Object> map2 : userRole) {
			roleFw = map2.get("ROLE_FW") + roleFw;
			if (map2.get("ROLE_ID") != null && map2.get("ROLE_ID").toString().equals(Constants.ADMIN_ROLE)) {
				roleCd = Constants.ADMIN_ROLE;
			}
		}
		if (roleFw.contains(Constants.ROLE_FW_1)) {// 所有

		} else if (roleFw.equals(Constants.ROLE_FW_2)) { // 本级及下级
			String childIds = lrdOrgService.getChilds(user.getOrgCD());
			map.put("orgCds", "(" + childIds + ")");
		} else if (roleFw.contains(Constants.ROLE_FW_0)) {// 本级
			String orgCD = user.getOrgCD();
			map.put("orgCd", orgCD);
		}
		List<Map<String, Object>> resultList = lrdOrgMapper.findMenu(map);
		if (!Constants.ADMIN_ROLE.equals(roleCd)) {
			map.put("isAdmin", "false");
		}
		List<Map<String, Object>> resultRole = lrdRoleMapper.queryList(map);
		resultmap.put("org", resultList);
		resultmap.put("role", resultRole);
		resultmap.put("corpCd", user.getCorpCD());
		return ResultGenerator.genSuccessResult(resultmap);
	}

	@Transactional
	@Override
	public Result insertUser(LrdUser user) {
		LrdUser lrdUser = lrdUserMapper.selectByPrimaryKey(user.getUserId());
		if (lrdUser != null) {
			return ResultGenerator.genFailResult("登陆账号已经存在");
		}
		String newpwd = MD5.getMD5(Constants.PASSWORD);
		user.setJlFlag("1");
		user.setPassword(newpwd);
		save(user);
		// 先删除再插入
		Condition condition = new Condition(LrdUserrole.class);
		Criteria criteria = condition.createCriteria();
		if (StringUtils.isNotBlank(user.getCorpCd())) {
			criteria.andCondition("CORP_CD=",user.getCorpCd());
		}
		if (StringUtils.isNotBlank(user.getUserId())) {
			criteria.andCondition("USER_ID=",user.getUserId());
		}
		lrdUserroleMapper.deleteByExample(condition);
		List<String> roleCds=user.getRoleCds();
		for (int i = 0; i < roleCds.size(); i++) {
			LrdUserrole lrdUserrole = new LrdUserrole();
			lrdUserrole.setUserId(user.getUserId());
			lrdUserrole.setRoleId(roleCds.get(i));
			lrdUserrole.setCorpCd(user.getCorpCd());
			lrdUserroleMapper.insert(lrdUserrole);
		}
		sendUserToWx(user);
		return ResultGenerator.genSuccessResult();
	}

	public void sendUserToWx(LrdUser lrdUser){
		UserInfo info = new UserInfo();
		info.setModelType("xzyhxx");//添加用户信息
		info.setManagerId(lrdUser.getUserId());
		info.setIdNo(lrdUser.getIdNo());
		info.setUserName(lrdUser.getUserName());
		SendHttpService.sendHttp(info);	//用户信息同步到微信
	}

	@Transactional
	@Override
	public Result updateUser(LrdUser user) {	
		update(user);
		// 先删除再插入
		Condition condition = new Condition(LrdUserrole.class);
		Criteria criteria = condition.createCriteria();
		if (StringUtils.isNotBlank(user.getCorpCd())) {
			criteria.andCondition("CORP_CD=",user.getCorpCd());
		}
		if (StringUtils.isNotBlank(user.getUserId())) {
			criteria.andCondition("USER_ID=",user.getUserId());
		}
		lrdUserroleMapper.deleteByExample(condition);

		List<String> roleCds=user.getRoleCds();
		for (int i = 0; i < roleCds.size(); i++) {
			LrdUserrole lrdUserrole = new LrdUserrole();
			lrdUserrole.setUserId(user.getUserId());
			lrdUserrole.setRoleId(roleCds.get(i));
			lrdUserrole.setCorpCd(user.getCorpCd());
			lrdUserroleMapper.insert(lrdUserrole);
		}
		//同步到微信
		sendUserToWx(user);
		return ResultGenerator.genSuccessResult();
	}

	@Transactional
	@Override
	public Result deleteUserAndRole(String userId) {
		LrdUser lrdUser = new LrdUser();
		lrdUser.setUserId(userId);
		lrdUserMapper.delete(lrdUser);
		LrdUserrole lrdUserrole = new LrdUserrole();
		lrdUserrole.setUserId(userId);
		lrdUserroleMapper.delete(lrdUserrole);
		//同步微信
		UserInfo info = new UserInfo();
		info.setModelType("scyhxx");//删除用户信息
		info.setManagerId(userId);
		SendHttpService.sendHttp(info);

		return ResultGenerator.genSuccessResult();
	}

	@Override
	public LrdUser getUserByUsername(String userId) {
		LrdUser user = findById(userId);
		return user;
	}

	@Override
	public Result queryOrgTree(HttpServletRequest request) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		if (!Constants.SLS_CORP.equals(user.getCorpCD())) {
			map.put("corpCd", user.getCorpCD());
		}
		List<Map<String, Object>> userRole = user.getROLE_CD();
		String roleFw = "";
		for (Map<String, Object> map2 : userRole) {
			roleFw = map2.get("ROLE_FW") + roleFw;
		}
		if (roleFw.contains(Constants.ROLE_FW_1)) {// 所有

		} else if (roleFw.equals(Constants.ROLE_FW_2)) { // 本级及下级
			String childIds = lrdOrgService.getChilds(user.getOrgCD());
			map.put("orgCds", "(" + childIds + ")");
		} else if (roleFw.contains(Constants.ROLE_FW_0)) {// 本级
			String orgCD = user.getOrgCD();
			map.put("orgCd", orgCD);
		}
		List<Map<String, Object>> orgTree = lrdOrgMapper.findMenu(map);
		return ResultGenerator.genSuccessResult(orgTree);
	}

	@Override
	public Result updatePwd(HttpServletRequest request, Map<String, Object> map) {
		User user = (User) request.getSession().getAttribute("user");
		LrdUser lrdUser = getUserByUsername(user.getUser_id());
		String oldPassWord = MD5.getMD5(Base64.decode(map.get("oldPassWord").toString()));
		if (!lrdUser.getPassword().equals(oldPassWord)) {
			return ResultGenerator.genFailResult("原密码不正确");
		}
		String newPassWord = MD5.getMD5(Base64.decode(map.get("newPassWord").toString()));
		lrdUser.setPassword(newPassWord);
		int n = lrdUserMapper.updateByPrimaryKeySelective(lrdUser);
		if (n > 0) {
			return ResultGenerator.genSuccessResult();
		} else {
			return ResultGenerator.genFailResult("修改失败");
		}
	}

	@Override
	public Result queryRoleList(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = (User) request.getSession().getAttribute("user");
		List<Map<String, Object>> userRole = user.getROLE_CD();
		String roleCd = "";
		for (Map<String, Object> map2 : userRole) {
			if (map2.get("ROLE_ID") != null && map2.get("ROLE_ID").toString().equals(Constants.ADMIN_ROLE)) {
				roleCd = Constants.ADMIN_ROLE;
			}
		}
		if (!Constants.ADMIN_ROLE.equals(roleCd)) {
			map.put("isAdmin", "false");
		}
		List<Map<String, Object>> resultRole = lrdRoleMapper.queryList(map);
		return ResultGenerator.genSuccessResult(resultRole);
	}

	@Override
	public List<LrdUser> selectAll() {
		return findAll();
	}

	@Override
	public List<LrdUser> findBranchManagerByOrgCd(String corpCd, String orgCd, String roleId) {
		return lrdUserMapper.findBranchManagerByOrgCd(corpCd,orgCd,roleId);
	}
}
